using System.Text;
using System.Xml;
using Microsoft.International.Converters.PinYinConverter;

namespace HelloDict.Core;

public static class QueryInter
{
    public static Entry Word(string keywords)
    {
        var entry = new Entry();
        XmlDocument xmlDocument = new XmlDocument();
        try
        {
            xmlDocument.Load(Environment.CurrentDirectory+$"/xdhycd7/{keywords}.xml");
            entry.Word = keywords;
            entry.Definition =
            [
                xmlDocument.SelectSingleNode("/Entry/Definition").InnerText
            ];
        }
        catch (FileNotFoundException)
        {
            entry.Definition = ["查无此词"];
                
        }


        // string pinyin = ConvertToPinYin(keywords);
        // var entry = new Entry();
        // // entry.Word = pinyin;
        return entry;
    }

    private static string ConvertToPinYin(string chineseString)
    {
        StringBuilder result = new StringBuilder();
        foreach (char item in chineseString)
        {
            string pinyin;
            try
            {
                ChineseChar chineseChar = new ChineseChar(item);
                pinyin = chineseChar.Pinyins.First().ToLower();
                pinyin = pinyin.Substring(0, pinyin.Length - 1);
            }
            catch (NotSupportedException)
            {
                pinyin = item.ToString();
            }

            result.Append(pinyin);
        }

        return result.ToString();
    }
}